<template>
  <!-- 搜索栏 -->

  <div class="search-continer">
    <!-- 搜索栏 -->
    <!-- Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
    <form action="/">
      <van-search
        v-model="selectVal"
        class="search"
        shape="square"
        :show-action="true"
        background="#5babfb"
        placeholder="请输入搜索关键词"
        @search="sousuo"
        @focus="jiaodian"
      >
        <template slot="action">
          <div @click="onSearch" class="clearBtn">取消</div>
        </template>
      </van-search>
    </form>
    <!-- /搜索栏 -->

    <!-- 搜索栏 -->
    <Searchlan v-if="isSearch" :selectVal="selectVal" />
    <!-- 搜索联想 -->
    <Searchxiang
      @queding="queding"
      :selectVal="selectVal"
      v-else-if="selectVal.trim()"
    />
    <!-- 搜索历史 -->
    <Searchli
      @delLi="delLi"
      @delLiAll="delLiAll"
      :lishiList="lishiList"
      v-else
    />
  </div>
</template>

<script>
import Searchlan from "./component/Search-lan.vue";
import Searchxiang from "./component/Search-xiang.vue";
import Searchli from "./component/Search-li.vue";
import { setItem, getItem, removeItem } from "@/utils/storage.js";
export default {
  data() {
    return {
      selectVal: "",
      isSearch: false,
      lishiList: getItem("lishi") ? getItem("lishi") : [],
    };
  },
  watch: {
    lishiList(val) {
      setItem("lishi", val);
    },
  },
  methods: {
    onSearch() {
      this.$router.back();
    },
    //开始搜索
    sousuo() {
      if (this.lishiList.indexOf(this.selectVal) === -1) {
        this.lishiList.unshift(this.selectVal);
      }
      this.isSearch = true;
    },
    //获取焦点
    jiaodian() {
      this.isSearch = false;
    },
    //搜索
    queding(text) {
      this.isSearch = true;
      this.selectVal = text;
      if (this.lishiList.indexOf(this.selectVal) === -1) {
        this.lishiList.unshift(this.selectVal);
      }
    },
    //删除单个历史
    delLi(val) {
      let index = this.lishiList.findIndex((item) => item === val);
      this.lishiList.splice(index, 1);
    },
    delLiAll() {
      this.lishiList = [];
    },
  },
  components: {
    Searchlan,
    Searchxiang,
    Searchli,
  },
};
</script>

<style lang="less" scoped>
.search-continer {
  margin-top: 105px;
  /deep/.van-search__content {
    width: 590px;
    flex: none;
  }
  .search {
    position: fixed;
    top: 0;
    z-index: 1;
    left: 0;
    right: 0;
  }
  .van-search__action {
    flex: 1;
  }
  .clearBtn {
    color: #fff;
    text-align: center;
    font-size: 28px;
  }
  .van-cell {
    align-items: center;
  }
}
</style>